<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import {
  ElSelect,
  ElOption,
  ElButton,
  ElMessage,
  ElForm,
  ElFormItem,
  ElDatePicker,
  ElTable,
  ElTableColumn,
  ElTag,
  ElMessageBox
} from 'element-plus'
import { Dialog } from '@/components/Dialog'
import { formatToDate } from '@/utils/dateUtil'
import {
  queryUserListApi,
  queryCustListApi,
  queryBindInfoApi,
  createBindInfoApi
} from '@/api/exdoctor'
import { BindData, NewBindItem, UserItem } from './types'

const userList = ref<UserItem[]>([])

const bindData = reactive<BindData>({
  userId: undefined,
  getLoading: false,
  currentBind: [],
  historyBinds: [],
  historyBindsTotal: 0,
  currentPage: 1,
  pageSize: 10
})

const newBindData = reactive<NewBindItem>({
  visible: false,
  bindLoading: false,
  cust_num: '',
  start_date: undefined,
  end_date: undefined,
  custList: []
})

// 逻辑
const getUserList = (kw: string) => {
  queryUserListApi({ kw }).then((res) => {
    userList.value = res.data.rows
  })
}

const getCustNumList = (kw: string) => {
  queryCustListApi(kw).then((res) => {
    newBindData.custList = res.data
  })
}

const toQueryBindInfo = () => {
  if (!bindData.userId) return
  bindData.getLoading = true
  queryBindInfoApi(bindData.userId).then((res) => {
    const resData = res.data
    bindData.currentBind = resData.active_list
    bindData.historyBinds = resData.history_list
    bindData.getLoading = false
  })
}

const toSaveNewBind = () => {
  ElMessageBox.confirm('确定绑定吗？绑定后旧绑定都将失效!', '确认', {
    confirmButtonText: '绑定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    if (!newBindData.cust_num || !bindData.userId) {
      ElMessage.error('请确定用户和资金号再绑定!')
      return
    }
    newBindData.bindLoading = true
    createBindInfoApi({
      user_id: bindData.userId,
      cust_num: newBindData.cust_num,
      start_date: newBindData.start_date ? formatToDate(newBindData.start_date) : null,
      end_date: newBindData.end_date ? formatToDate(newBindData.end_date) : null
    })
      .then((res) => {
        ElMessage.success(res.message)
        newBindData.visible = false
        newBindData.bindLoading = false
      })
      .catch(() => {
        newBindData.bindLoading = false
      })
  })
}

watch(
  () => bindData.userId,
  () => {
    if (!bindData.userId) return
    toQueryBindInfo()
  },
  {
    immediate: true
  }
)
</script>
<template>
  <div class="view-container">
    <div class="param-actions">
      <ElSelect
        v-model="bindData.userId"
        placeholder="请输入用户手机号查询"
        no-data-text="查无此用户"
        filterable
        clearable
        remote
        style="width: 300px"
        :remote-method="getUserList"
      >
        <ElOption
          v-for="u in userList"
          :key="u.id"
          :value="u.id"
          :label="`${u.nickname}(${u.username})`"
        />
      </ElSelect>
      <ElButton
        type="primary"
        class="ml-10px"
        :loading="bindData.getLoading"
        @click="toQueryBindInfo"
      >
        查询
      </ElButton>
      <ElButton
        type="success"
        class="ml-10px"
        :loading="bindData.getLoading"
        :disabled="!bindData.userId"
        @click="newBindData.visible = true"
      >
        新的绑定
      </ElButton>
    </div>
    <div class="mt-10px">
      <div>当前绑定情况：</div>
      <ElTable border empty-text="暂无绑定资金号" :data="bindData.currentBind">
        <ElTableColumn prop="create_time" label="创建时间" />
        <ElTableColumn prop="cust_num" label="资金号" />
        <ElTableColumn prop="start_date" label="开始日期" />
        <ElTableColumn prop="end_date" label="结束日期" />
        <ElTableColumn label="有效">
          <template #default="scope">
            <ElTag :type="scope.row.is_active ? 'success' : 'danger'">
              {{ scope.row.is_active ? '生效中' : '失效' }}
            </ElTag>
          </template>
        </ElTableColumn>
      </ElTable>
    </div>
    <div class="mt-10px">
      <div>历史绑定记录：</div>
      <ElTable border empty-text="没有历史绑定记录" :data="bindData.historyBinds">
        <ElTableColumn prop="create_time" label="创建时间" />
        <ElTableColumn prop="cust_num" label="资金号" />
        <ElTableColumn prop="start_date" label="开始日期" />
        <ElTableColumn prop="end_date" label="结束日期" />
        <ElTableColumn label="有效">
          <template #default="scope">
            <ElTag :type="scope.row.is_active ? 'success' : 'danger'">
              {{ scope.row.is_active ? '生效中' : '失效' }}
            </ElTag>
          </template>
        </ElTableColumn>
      </ElTable>
    </div>
    <Dialog v-model="newBindData.visible" title="绑定新的资金号">
      <div>
        <ElForm>
          <ElFormItem label="资金账号">
            <ElSelect
              v-model="newBindData.cust_num"
              filterable
              remote
              :remote-method="getCustNumList"
            >
              <ElOption
                v-for="c in newBindData.custList"
                :key="c.fund_num"
                :label="c.fund_num"
                :value="c.fund_num"
              />
            </ElSelect>
          </ElFormItem>
          <ElFormItem label="开始日期">
            <ElDatePicker v-model="newBindData.start_date" :clearable="false" />
          </ElFormItem>
          <ElFormItem label="结束日期">
            <ElDatePicker v-model="newBindData.end_date" :clearable="true" />
          </ElFormItem>
          <div>
            <p>1. 开始日期必须设置</p>
            <p>2. 结束日期若无设置，则表示能诊断到最新日期</p>
            <p>3. 新的绑定成功，原来的所有绑定都将失效</p>
          </div>
        </ElForm>
      </div>
      <template #footer>
        <ElButton @click="newBindData.visible = false">关闭</ElButton>
        <ElButton type="primary" :loading="newBindData.bindLoading" @click="toSaveNewBind">
          确认绑定
        </ElButton>
      </template>
    </Dialog>
  </div>
</template>
<style scoped lang="less">
.view-container {
  .param-actions {
    display: flex;
    align-items: center;
  }
}
</style>
